package com.seedwill.common.security;

import java.security.KeyPair;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.compass.core.util.Assert;

import de.bsi.shellycoat.common.CryptHelper;

/**
 * 加解密安全服务
 * 
 * @author kdyi
 *
 */
public class SecurityServiceImpl implements ISecurityService {
    /**
     * 日志
     */
    private static final Log logger = LogFactory.getLog(SecurityServiceImpl.class);
    
	/**
	 * 密钥文件
	 * 用XStream序列化的KeyPair对象
	 */
	private String keyFile;
 
	public String getKeyFile() {
		return keyFile;
	}

	public void setKeyFile(String keyFile) {
		this.keyFile = keyFile;
	}

	/**
	 * XStream服务
	 */
	private com.thoughtworks.xstream.XStream xstreamService;
	
	public com.thoughtworks.xstream.XStream getXstreamService() {
		return xstreamService;
	}

	public void setXstreamService(com.thoughtworks.xstream.XStream xstreamService) {
		this.xstreamService = xstreamService;
	}

	/**
	 * 加密
	 */
	private CryptHelper cryptHelper = CryptHelper.instance();
	
	/**
	 * 加解密密钥
	 */
	private KeyPair keyPair;
	
	/**
	 * 生成加解密密钥
	 */
	public void postKeyPair(){
		try {
			KeyPair keyPairInner = cryptHelper.generateKeyPair();
			java.io.FileOutputStream streamOut = new java.io.FileOutputStream(keyFile);
			xstreamService.toXML(keyPairInner, streamOut);
		} catch (Exception e) {
			logger.warn("postKeyPair", e);
		}
		
	}
	
	/**
	 * 获取加解密密钥
	 * @return
	 */
	public KeyPair getKeyPair(){
		KeyPair keyPairInner = null;
		try {
			java.io.FileInputStream input = new java.io.FileInputStream(keyFile);
			keyPairInner = (KeyPair) xstreamService.fromXML(input);
			return keyPairInner;
		} catch (Exception e) {
			logger.warn("getKeyPair", e);
		}
		return keyPairInner;
	}
	
	/**
	 * 初始化
	 */
	public void init(){
		if(keyFile != null){
			java.io.File kf = new java.io.File(keyFile);
			if(kf.exists() && kf.canRead()){
				keyPair = getKeyPair();
			}else{
				postKeyPair();
				kf = new java.io.File(keyFile);
			}
			if(kf.exists() && kf.canRead()){
				keyPair = getKeyPair();
			}
		}
	
	}

	@Override
	public String decrypt(String str) {
		if(keyPair == null && keyFile != null){
			init();
		}
		Assert.notNull(keyPair, "加密KEY不能为空");
		Assert.notNull(str, "解密对象不能为空");
		
		return cryptHelper.decryptAsymmetric(keyPair.getPrivate(), str);
	}

	@Override
	public String encrypt(String str) {
		if(keyPair == null && keyFile != null){
			init();
		}
		Assert.notNull(keyPair, "加密KEY不能为空");
		Assert.notNull(str, "加密对象不能为空");
		return cryptHelper.encryptAsymmetric(keyPair.getPublic(), str);
	}
 
}
